package controllers

import (
	"AndroidBlog/models"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/httplib"
	"strings"
)

type CWanandroid struct {
}

func (c *CWanandroid) doCrawl() (string) {
	return ""
}

func doCrawlWanandroid(page int) (string) {
	var count = page
	formatUrl := "http://www.wanandroid.com/article/list/%d/json"
	strarr := []string{}
	for i := 1; i <= count; i++ {
		url := fmt.Sprintf(formatUrl, i)
		fmt.Println("url=> ", url)
		req := httplib.Get(url)
		str, err := req.String()
		fmt.Println("result=> ", str)
		checkErr(err)
		//strarr = append(strarr,str)
		parseInsertWanandroid(str)
		strarr = append(strarr, str)
	}
	str3 := strings.Join(strarr, " \r\n --- \r\n")
	return str3
}

func parseInsertWanandroid(str string) {
	var res WanResp
	data := []byte(str)
	err := json.Unmarshal(data, &res)
	if err == nil {
		if res.ErrorCode == 0 && res.Data.Datas != nil {
			list := res.Data.Datas
			length := len(list)
			for i := 0; i < length; i++ {
				item := list[i]
				ii := models.Article{}
				ii.Author = item.Author
				ii.CrateTime = item.PublishTime
				ii.Link = item.Link
				ii.Title = item.Title
				ii.Source = item.SuperChapterName
				ii.Description = ""
				idd:=models.ArticleInsertOrUpdate(ii)
				fmt.Println("inserid ", idd)
			}
		}
	}

}

type WanArticle struct {
	Id               int    `orm:"column(id);pk"`
	ApkLink          string `json:"apkLink"`
	Author           string `json:"author"`
	ChapterId        int    `json:"chapterId"`
	ChapterName      string `json:"chapterName"`
	Collect          bool   `json:"collect"`
	CourseId         int    `json:"courseId"`
	Desc             string `json:"desc"`
	EnvelopePic      string `json:"envelopePic"`
	Fresh            bool   `json:"fresh"`
	Link             string `json:"link"`
	NiceDate         string `json:"niceDate"`
	Origin           string `json:"origin"`
	ProjectLink      string `json:"projectLink"`
	PublishTime      int64  `json:"publishTime"`
	SuperChapterId   int    `json:"superChapterId"`
	SuperChapterName string `json:"superChapterName"`
	Title            string `json:"title"`
	Atype            int    `json:"type"`
	UserId           int    `json:"userId"`
	Visible          int    `json:"visible"`
	Zan              int    `json:"zan"`
}
type WanListResp struct {
	CurPage   int          `json:"curPage"`
	Datas     []WanArticle `json:"datas"`
	Offset    int          `json:"offset"`
	Over      bool         `json:"over"`
	PageCount int          `json:"pageCount"`
	Total     int          `json:"total"`
	Size      int          `json:"size"`
	//"offset": 20,
	//"over": false,
	//"pageCount": 291,
	//"size": 20,
	//"total": 5813
}
type WanResp struct {
	ErrorCode int         `json:"errorCode"`
	ErrorMsg  string      `json:"errorMsg"`
	Data      WanListResp `json:"data"`
}
